<template>
    <Dialog v-model="dialogVisible" :title="dialogTitle" width="65%">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px" v-loading="formLoading">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="拼团名称" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入拼团名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="关联门店" prop="storeId">
                        <el-select v-model="formData.storeId" placeholder="请选择门店">
                            <el-option v-for="item in storeList" :label="item.label" :value="item.value" :key="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="24">
                    <el-form-item label="类型" prop="type">
                        <el-radio-group v-model="formData.type">
                            <el-radio v-for="item in getIntDictOptions(DICT_TYPE.PROMOTION_COMBINATION_ACTIVITY_TYPE)" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <template v-if="formData.type == '2'">
                    <el-col :span="12">
                        <el-form-item label="活动开始时间" prop="startTime">
                            <el-date-picker class="w-100%!" v-model="formData.startTime" value-format="x" type="date" placeholder="请选择活动开始时间" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动结束时间" prop="endTime">
                            <el-date-picker class="w-100%!" v-model="formData.endTime" value-format="x" type="date" placeholder="请选择活动结束时间" />
                        </el-form-item>
                    </el-col>
                </template> -->
                <el-col :span="12">
                    <el-form-item label="参与人数" prop="userSize">
                        <!-- <template #label>
                            <div class="flex flex-items-center">
                                <span>参与人数<Icon class="c-blue" icon="ep:warning" /></span>
                            </div>
                        </template> -->
                        <div class="flex flex-items-center" style="width: 100%;">
                            <el-input-number v-model="formData.userSize" style="flex: 1;" :min="1" :max="12" />
                            <el-tooltip class="item" effect="dark" content="参与人数不能少于一人，最多十二人" placement="top">
                                <Icon class="c-blue" icon="ep:warning" style="margin-left: 5px;" />
                            </el-tooltip>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="限制时长(小时)" prop="limitDuration">
                        <el-input-number v-model="formData.limitDuration" :min="0" :max="99" />
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                    <el-form-item label="总限购数量" prop="totalLimitCount">
                        <el-input-number v-model="formData.totalLimitCount" :min="0" :max="99" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="单次限购数量" prop="singleLimitCount">
                        <el-input-number v-model="formData.singleLimitCount" :min="0" :max="99" />
                    </el-form-item>
                </el-col> -->
                <!-- <el-col :span="24">
                    <el-form-item label="拼团价格" prop="priceList">
                        <div class="w-23% flex flex-items-center p-r-2% mb-10px" v-for="item, index in formData.priceList" :key="index">
                            <el-input-number v-model="formData.priceList[index]" :maxlength="100" :placeholder="`${index + 1}人成团的价格`" />
                        </div>
                    </el-form-item>
                </el-col> -->
                <el-col :span="24">
                    <el-form-item label="客服二维码" prop="qrcode">
                        <el-select v-model="formData.qrcode" placeholder="请选择客服二维码" @change="handleChangeQrcode">
                            <el-option v-for="item in qrcodeList" :label="item.codeName" :value="item.id + ''" :key="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="分享海报图">
                        <UploadImg v-model="formData.posterUrl" height="80px" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="拼团介绍" prop="descrptList">
                        <div class="w-100% flex flex-items-center mb-10px" v-for="item, index in formData.descrptList" :key="index">
                            <el-input v-model="formData.descrptList[index]" :maxlength="100" placeholder="请输入拼团介绍" />
                            <Icon class="ml-5px c-red cursor-pointer" icon="ep:delete" @click="handleDelete('descrptList', index)" />
                        </div>
                        <el-button class="button-new-tag ml-1" size="small" @click="handleAdd('descrptList')">+ 添加</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="拼团课程">
                        <el-button @click="spuSelectRef.open()">选择课程</el-button>
                        <SpuAndSkuList ref="spuAndSkuListRef" :rule-config="ruleConfig" :spu-list="spuList" :spu-property-list-p="spuPropertyList">
                            <!-- <el-table-column align="center" label="拼团价格(元)" min-width="168"> -->
                            <el-table-column type="expand" width="30" align="center">
                                <template #default="{ row: sku }">
                                    <div class="flex flex-items-center flex-wrap">
                                        <div class="w-25% pl-5px pr-5px mt-5px mb-5px" v-for="item, index in sku.productConfig.priceList" :key="index">
                                            <el-input-number v-model="sku.productConfig.priceList[index]" :maxlength="100" :placeholder="`${index + 1}人成团的价格`" />
                                        </div>
                                    </div>
                                    <!-- <el-input-number v-model="sku.productConfig.combinationPrice" :min="0" :precision="2"
                                        :step="0.1" class="w-100%" /> -->
                                </template>
                            </el-table-column>
                        </SpuAndSkuList>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <!-- <Form ref="formRef" v-loading="formLoading" :is-col="true" :rules="rules" :schema="allSchemas.formSchema"
            class="mt-10px">
            <template #price="{ price }">
                <div class="w-100% flex flex-items-center mb-10px" v-for="item, index in price">
                    <el-input v-model="price[index]" :maxlength="100" :placeholder="`${index + 1}人成团的价格`" />
                </div>
            </template>
            <template #description="{ description }">
                <div class="w-100% flex flex-items-center mb-10px" v-for="item, index in description">
                    <el-input v-model="description[index]" :maxlength="100" placeholder="请输入拼团介绍" />
                    <Icon class="ml-5px c-red cursor-pointer" icon="ep:delete" @click="handleDelete(index)" />
                </div>
                <el-button class="button-new-tag ml-1" size="small" @click="handleAdd">+ 添加</el-button>
            </template>
            <template #spuId>
                <el-button @click="spuSelectRef.open()">选择课程</el-button>
                <SpuAndSkuList ref="spuAndSkuListRef" :rule-config="ruleConfig" :spu-list="spuList"
                    :spu-property-list-p="spuPropertyList">
                    <el-table-column align="center" label="拼团价格(元)" min-width="168">
                        <template #default="{ row: sku }">
                            <el-input-number v-model="sku.productConfig.combinationPrice" :min="0" :precision="2"
                                :step="0.1" class="w-100%" />
                        </template>
                    </el-table-column>
                </SpuAndSkuList>
            </template>
        </Form> -->
        <template #footer>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </template>
    </Dialog>
    <SpuSelect ref="spuSelectRef" :radio="true" :isSelectSku="true" @confirm="selectSpu" />
</template>
<script lang="ts" setup>
import * as CombinationActivityApi from '@/api/mall/promotion/combination/combinationActivity'
import { CombinationProductVO } from '@/api/mall/promotion/combination/combinationActivity'
import { rules } from './combinationActivity.data'
import { SpuAndSkuList, SpuProperty, SpuSelect } from '@/views/mall/promotion/components'
import { getPropertyList, RuleConfig } from '@/views/mall/product/spu/components'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as QrcodeApi from '@/api/system/qrcode'
import * as StoreApi from '@/api/system/store'
import { yuanToFen, fenToYuan } from '@/utils'
import { cloneDeep } from 'lodash-es'

defineOptions({ name: 'PromotionCombinationActivityForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref

/** 初始化表单 */
function getForm() {
    return {
        name: '',
        storeId: '',
        type: 1,
        startTime: '',
        endTime: '',
        userSize: 2,
        qrcode: '',
        qrcodeName: '',
        posterUrl: '',
        limitDuration: 0,
        totalLimitCount: 0,
        singleLimitCount: 0,
        // priceList: [undefined, undefined],
        descrptList: [],
        spuId: undefined,
    }
}
const formData = ref<CombinationActivityApi.CombinationActivityVO>(getForm())

/** 根据参与人数设置拼团价格数组 */
const setPriceByUserSize = () => {
    let num = formData.value.userSize || 0, arr: Array<any> = [];
    for (let i = 0; i < num; i++) {
        arr.push('');
    }

    return arr;
}

/** 新增子项 */
const handleAdd = (key: string) => {
    formData.value[key].push('');
    // let description = unref(formRef.value.formModel).description;
    // description.push('')
    // formRef.value.setValues({ description })
}

/** 删除子项 */
const handleDelete = (key: string, index: number) => {
    formData.value[key].splice(index, 1);
    // let description = unref(formRef.value.formModel).description;
    // description?.splice(index, 1);
    // formRef.value.setValues({ description })
}

/** 查询门店 */
const storeList = ref([]);
const getStoreList = () => {
    StoreApi.getStoreAllList().then(res => {
        storeList.value = res.map(item => {
            return {
                label: item.storeName,
                value: item.id
            }
        })
    })
}

/** 查询二维码 */
const qrcodeList = ref<QrcodeApi.Qrcode[]>([]);
const getQrcodeList = () => {
    QrcodeApi.getQrcodeList({
        pageNo: 1,
        pageSize: 100
    }).then(res => {
        qrcodeList.value = res.list;
    })
}
function handleChangeQrcode(value) {
    let item = qrcodeList.value.find(item => item.id == value);
    if (item) {
        formData.value.qrcodeName = item.codeName;
    }
}

// ================= 课程选择相关 =================

const spuSelectRef = ref() // 课程和属性选择 Ref
const spuAndSkuListRef = ref() // sku 秒杀配置组件Ref
const spuList = ref<CombinationActivityApi.SpuExtension[]>([]) // 选择的 spu
const spuPropertyList = ref<SpuProperty<CombinationActivityApi.SpuExtension>[]>([])
const ruleConfig: RuleConfig[] = [
    {
        name: 'productConfig.priceList',
        rule: (arg) => {
            let num = 0;
            arg.forEach(item => {
                if (item >= 0.01) {
                    num++;
                }
            })
            return arg.length === num;
        },
        message: '课程拼团价格不能小于0.01 ！'
    }
]
const selectSpu = (spuId: number, skuIds: number[]) => {
    // formRef.value.setValues({ spuId })
    formData.value.spuId = spuId;
    getSpuDetails(spuId, skuIds)
}
watch(() => formData.value.userSize, (val, old) => {
    let num = val || 0, arr: Array<any> = [];
    for (let i = 0; i < num; i++) {
        arr.push('');
    }
    // formData.value.priceList = arr;
    if (spuList.value.length) {
        spuList.value[0].skus.forEach(item => {
            item.productConfig.priceList = arr.concat();
        })
    }
}, {
    immediate: true
})
/**
 * 获取 SPU 详情
 */
const getSpuDetails = async (
    spuId: number,
    skuIds: number[] | undefined,
    products?: CombinationProductVO[]
) => {
    const spuProperties: SpuProperty<CombinationActivityApi.SpuExtension>[] = []
    const res = (await ProductSpuApi.getSpuDetailList([
        spuId
    ])) as CombinationActivityApi.SpuExtension[]
    if (res.length == 0) {
        return
    }
    spuList.value = []
    // 因为只能选择一个
    const spu = res[0]
    const selectSkus =
        typeof skuIds === 'undefined' ? spu?.skus : spu?.skus?.filter((sku) => skuIds.includes(sku.id!))
    selectSkus?.forEach((sku) => {
        let config: CombinationProductVO = {
            spuId: spu.id!,
            skuId: sku.id!,
            combinationPrice: '',
            priceList: setPriceByUserSize()
        }
        if (typeof products !== 'undefined') {
            const product = products.find((item) => item.skuId === sku.id)
            if (product) {
                product.priceList = product.priceList?.map(item => {
                    return fenToYuan(item)
                }) || setPriceByUserSize();
                product.combinationPrice = fenToYuan(product.combinationPrice)
            }
            config = product || config
        }
        sku.productConfig = config

        sku.price = fenToYuan(sku.price)
        sku.marketPrice = fenToYuan(sku.marketPrice)
        sku.costPrice = fenToYuan(sku.costPrice)
        sku.firstBrokeragePrice = fenToYuan(sku.firstBrokeragePrice)
        sku.secondBrokeragePrice = fenToYuan(sku.secondBrokeragePrice)
    })
    spu.skus = selectSkus as CombinationActivityApi.SkuExtension[]
    spuProperties.push({
        spuId: spu.id!,
        spuDetail: spu,
        propertyList: getPropertyList(spu)
    })
    spuList.value.push(spu)
    spuPropertyList.value = spuProperties
}

// ================= end =================

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    await resetForm()
    // 修改时，设置数据
    if (id) {
        // formLoading.value = true
        try {
            const data = (await CombinationActivityApi.getCombinationActivity(
                id
            )) as CombinationActivityApi.CombinationActivityVO
            
            formData.value = data;
            await getSpuDetails(data.spuId!, data.products?.map((sku) => sku.skuId), data.products)
            // formRef.value.setValues(data)
        } finally {
            // formLoading.value = false
        }
    }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = async () => {
    spuList.value = []
    spuPropertyList.value = []
    formData.value = getForm();
    await nextTick()
    // formRef.value.getElFormRef().resetFields()
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
    // 校验表单
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    // 提交请求
    formLoading.value = true
    try {
        // 获得拼团课程配置
        const products = cloneDeep(spuAndSkuListRef.value.getSkuConfigs('productConfig'))
        products.forEach((item: CombinationActivityApi.CombinationProductVO) => {
            item.priceList = item.priceList.map((item) => {
                return yuanToFen(item)
            })
            item.combinationPrice = yuanToFen(item.combinationPrice)
        })
        const data = cloneDeep(formData.value) as CombinationActivityApi.CombinationActivityVO

        /** 拼团介绍转换为字符串 */
        // data.descrptList = window.JSON.stringify(data.descrptList);
        // data.priceList.forEach((item) => {
        //     item = item.toString();
        // })

        data.products = products
        // 真正提交
        if (formType.value === 'create') {
            await CombinationActivityApi.createCombinationActivity(data)
            message.success(t('common.createSuccess'))
        } else {
            await CombinationActivityApi.updateCombinationActivity(data)
            message.success(t('common.updateSuccess'))
        }
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
    } finally {
        formLoading.value = false
    }
}

/** 初始化 **/
onMounted(() => {
    getStoreList();
    getQrcodeList();
})
</script>
